﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FrameLinePanel : MonoBehaviour
{
    public FrameLineItem prefab;
    public Transform viewRoot;
    public Transform cacheRoot;

    private UIObjCacheProcess<FrameLineItem> itemPool;

    private void InitPool()
    {
        if (itemPool == null)
            itemPool = new UIObjCacheProcess<FrameLineItem>(cacheRoot, viewRoot, prefab);
    }
    private void OnEnable()
    {
        InitPool();
        EventManager.AddEventListener<ActionClipInfo, AnimClipInfo>(CommonEvent.OpenFrameLinePanel, RefreshFrameLinePanel);
    }

    private void OnDisable()
    {
        EventManager.RemoveEventListener<ActionClipInfo, AnimClipInfo>(CommonEvent.OpenFrameLinePanel, RefreshFrameLinePanel);
    }

    private void RefreshFrameLinePanel(ActionClipInfo actionClip, AnimClipInfo animClip)
    {
        if (actionClip == null)
        {
            RefreshAnimClip(animClip);
        }
        else if (animClip == null)
        {
            RefreshActionClip(actionClip);
        }
        else
        {
            FucTempLog.LogError("数据异常");
        }
    }

    private void RefreshActionClip(ActionClipInfo actionClip)
    {
        if (actionClip == null)
        {
            FucTempLog.LogError("ActionClipInfo null !");
        }
        else
        {
            itemPool.RecycleAll();
            var list = actionClip.GetFrameInfo();
            foreach (var frameData in list)
            {
                var item = itemPool.Spawn();
                item.gameObject.name = frameData.animName+"_" + frameData.FrameIndex;
                item.SetData(frameData);
            }
        }
    }

    private void RefreshAnimClip(AnimClipInfo animClip)
    {
        if (animClip == null)
        {
            FucTempLog.LogError("ActionClipInfo null !");
        }
        else
        {
            itemPool.RecycleAll();
            var list = animClip.GetFrameList();
            foreach (var frameData in list)
            {
                var item = itemPool.Spawn();
                item.gameObject.name = frameData.animName + "_" + frameData.FrameIndex;
                item.SetData(frameData);
            }
        }
    }
}
